package com.example.lib_mvp.httpUtil;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
 
public class FileUploadExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
 
        // 需要上传的文件
        File file = new File("D:/桌面文件/logo.png");
 
        // 创建RequestBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
 
        // 构建MultipartBody
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), requestBody)
                .build();
 
        // 构建Request
        Request request = new Request.Builder()
                .url("https://headsetapi.yuzhouxiong.net/api/upload/file")
                .addHeader("Authorization",
                        "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjM2MDgsInRpbWUiOjE3MzM1NDAxOTB9.2ptvBBovFNFISJCvCSOKKEX02MFMywXHhkzE366cUP4")
                .post(body)
                .build();
 
        try {
            // 发送请求
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println("File uploaded successfully");
            } else {
                System.out.println("Failed to upload file");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}